<template>
  <div>
    <a-card title="PDF文档内容搜索">
      <a-form layout="inline" @submit.prevent>
        <a-form-item label="关键字">
          <a-input v-model:value="keyword" placeholder="请输入搜索关键字" style="width: 300px" @pressEnter="handleSearch" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" :loading="loading" @click="handleSearch">搜索</a-button>
        </a-form-item>
      </a-form>
      <a-table :dataSource="results" :columns="columns" rowKey="documentId" style="margin-top: 16px;" />
    </a-card>
    <a-modal v-model:open="detailVisible" title="内容详情" width="60%">
      <div v-html="highlightedContent"></div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, h } from 'vue';
import { pdfApi } from '/@/api/business/pdf/pdf-api';
import { message } from 'ant-design-vue';
// defineOptions({ name: 'PdfSearch' });

const keyword = ref('');
const loading = ref(false);
const results = ref([]);
const detailVisible = ref(false);
const detailContent = ref('');

const columns = [
  { title: '文档ID', dataIndex: 'documentId', key: 'documentId', width: 100 },
  { title: '文件名', dataIndex: 'fileName', key: 'fileName', width: 200 },
  { title: '页码', dataIndex: 'pageNumber', key: 'pageNumber', width: 80 },
  {
    title: '内容片段',
    dataIndex: 'content',
    key: 'content',
    customRender: ({ text }) => text && text.length > 60 ? text.slice(0, 60) + '...' : text,
  },
  {
    title: '操作',
    key: 'action',
    width: 80,
    customRender: ({ record }) =>
      h('a', { style: 'cursor:pointer;color:#1677ff;', onClick: () => showDetail(record.content) }, '详情')
  }
];

function showDetail(content) {
  detailContent.value = content;
  detailVisible.value = true;
  console.log(keyword.value, detailContent.value)
}

const highlightedContent = computed(() => {
  if (!keyword.value) return detailContent.value;
  const safeKeyword = keyword.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const reg = new RegExp(safeKeyword, 'gi');
  return detailContent.value.replace(reg, (match) => `<span class="highlight">${match}</span>`);
});

async function handleSearch() {
  if (!keyword.value) {
    message.warning('请输入搜索关键字');
    return;
  }
  loading.value = true;
  try {
    const res = await pdfApi.search(keyword.value);
    results.value = res.data;
    if (!results.value.length) {
      message.info('未找到相关内容');
    }
  } catch (err) {
    message.error('搜索失败');
  } finally {
    loading.value = false;
  }
}
</script>

<style>
/* src/style.css 或 App.vue <style>（无scoped） */
.highlight {
  background: yellow !important;
  color: red !important;
  font-weight: bold !important;
  padding: 0 2px !important;
  border-radius: 2px !important;
  font-size: 18px !important;
  /* border: 2px solid blue !important; */
}
</style> 